/*
 * WideActivity serves as the interface between the user & the database. From WideActivity, a user can
 * update exisitnig inventory information, create new information, or destroy old information
 */
package com.example.wmuqrreader;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class WideActivity extends Activity {
	
	DatabaseHandler db;
	String inventory_id;
	String building_id;
	
	Button button_scan;		
	Button button_save; 	
	Button button_newa;		
	
	EditText editText_inv;	
	EditText editText_loc;	
	EditText editText_sn;
	EditText editText_type;
	EditText editText_brand;
	EditText editText_yr;
	EditText editText_svDate;
	
	Bundle extras;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_wide);	
		
		db = new DatabaseHandler(this);
		
		//Buttons - need functions
		button_scan 		= (Button) findViewById(R.id.btn_scan);
	    button_save 		= (Button) findViewById(R.id.btn_save);
	    button_newa 		= (Button) findViewById(R.id.btn_new);
	    
	    //Fields - will be populated later
	    editText_inv 		= (EditText) findViewById(R.id.editText_inv);
	    editText_loc		= (EditText) findViewById(R.id.editText_loc);
	    editText_sn			= (EditText) findViewById(R.id.editText_sn);
	    editText_type		= (EditText) findViewById(R.id.editText_type);
	    editText_brand		= (EditText) findViewById(R.id.editText_brand);
	    editText_yr			= (EditText) findViewById(R.id.editText_yr);
	    editText_svDate		= (EditText) findViewById(R.id.editText_svDate);	    	    	  
        
        extras = getIntent().getExtras();
        
        //ID Passed - existing inventory
        if (extras.getString("ID") != null )
        {
        	inventory_id = extras.getString("ID");
        	Log.d("GOT ID: ", inventory_id);
        	
        	populateFields(inventory_id);        	
			
			button_scan.setText("Delete");
			
			//Add a function for the SCAN button (renamed DELETE) click
            button_scan.setOnClickListener(new View.OnClickListener() {
    			
    			@Override
    			public void onClick(View v) {
    				Inventory delInv = populateInventory(Integer.parseInt(inventory_id));
    				db.deleteInventory(delInv);
    				
    				Toast.makeText(getApplicationContext(), "Entry destroyed", Toast.LENGTH_LONG).show();
    				
    				setResult(RESULT_OK, null);
    				finish();	       
    			}
    		});
        }
        //No ID passed - new inventory
        else
        {
        	//Auto populate Service Date with today's date
    	    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
    		Date date = new Date();
    		
    	    editText_svDate.setText(dateFormat.format(date));
    	    
    	    if(extras.getString("SCAN") != null)
    	    {
    	    	inventory_id = String.format("%5s:", extras.getString("QR") ).replace(' ', '0');
    	    	Log.d("GOT QR: ", inventory_id);
    	    	
    	    	editText_inv.setText(inventory_id);
    	    }    	        	   
    	    
    	    //Add a function for the SCAN button click
            button_scan.setOnClickListener(new View.OnClickListener() {
                            
                    @Override
                    public void onClick(View v) {
                            Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                            intent.setPackage("com.google.zxing.client.android");
                            intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
                            startActivityForResult(intent, 0);                     
                    }
             });
        }               
        
        if (extras.getString("BUILDING") != null )
        {
        	String building_id = extras.getString("BUILDING");
        	Log.d("GOT BUILDING: ", building_id);
        }               
        
        //Add a function for the NEW button click
        button_newa.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {			
					db.addInventory(populateInventory(0));
					
					//TODO: Handle case where ADD is clicked during edit. i.e: update current entry & open new editor
					Toast.makeText(getApplicationContext(), "New entry saved successfully", Toast.LENGTH_LONG).show();
					
					//Start new activity
					Intent intent = new Intent();
					
					intent.putExtra("BUILDING", building_id);
					
					intent.setClass(WideActivity.this, WideActivity.class);
			        startActivityForResult(intent, 0);
			        
			        setResult(RESULT_OK, null);
					finish();
				
				}
		});
        
        //Add a function for the SAVE button click
        button_save.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {	
				
				//If exists, update, else add
				if (extras.getString("ID") != null )
				{
					db.updateInventory( populateInventory( Integer.parseInt(extras.getString("ID")) ) );		
					Toast.makeText(getApplicationContext(), "Changes saved successfully", Toast.LENGTH_LONG).show();
				}
				else
				{
					db.addInventory( populateInventory(0) );		
					Toast.makeText(getApplicationContext(), "New entry added to the database", Toast.LENGTH_LONG).show();
				}
				
				setResult(RESULT_OK, null);
				finish();
			}
		});                      
	}

	//Populate the WideActivity fields from a given Inventory
	private void populateFields(String inventory_id) {
		
		Inventory entry = db.getInventory( Integer.parseInt(inventory_id) );		
		
    	editText_inv.setText( Integer.toString(entry.get_inv()) ); 
		editText_loc.setText( entry.get_location() );
		editText_sn.setText( entry.get_serialNum() );
		editText_type.setText( entry.get_type() );
		editText_brand.setText( entry.get_brand() );
		editText_yr.setText( entry.get_year() );
		editText_svDate.setText( entry.get_svDate() );
	}
	
	//Populate a new inventory object from field data
	private Inventory populateInventory(int id)
	{		
		String loc		= editText_loc.getText().toString();
		String sn		= editText_sn.getText().toString();
		String type 	= editText_type.getText().toString();
		String brand 	= editText_brand.getText().toString();
		String sd 		= editText_svDate.getText().toString();
		String yr 		= editText_yr.getText().toString();
		int inv			= Integer.parseInt( editText_inv.getText().toString() );
				
		
		if(id > 0) {	return new Inventory(id, loc, sn, type, brand, sd, yr, inv, 1);	}
		else {	return new Inventory(loc, sn, type, brand, sd, yr, inv, 1);	}
	}  

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0) 
        {
            if (resultCode == RESULT_OK) 
            {
            	Inventory inventory_scan;            	
                String contents = intent.getStringExtra("SCAN_RESULT");              
                              
                inventory_scan = db.getInventory( Integer.parseInt(contents) ); 
                if(inventory_scan.get_inv() == -1)
                {
                	Toast.makeText(getApplicationContext(), "Creating New...", Toast.LENGTH_LONG).show();
                }
                else
                	 Toast.makeText(getApplicationContext(), contents, Toast.LENGTH_LONG).show();
                
            } 
            else if (resultCode == RESULT_CANCELED) 
            {
                // Handle cancel
            }
        }
    }
}
